<?php
include($_SERVER["DOCUMENT_ROOT"] . "/bob.php");
include("fonctions_forum.php");
$mysqli = new_mysqli($host, $user, $password, $database); //connection à la DB
$variable_get = filter_input_array(INPUT_GET);
$variable_post = filter_input_array(INPUT_POST);

if (isset($variable_get['page'])) {
    $page = get_alphanum($variable_get['page']);
} else {
    $page = '';
}

$post_edit = get_post_get_num("pos");
$idtopic = get_post_get_num("topic");
$idforum = get_post_get_num("frum");
$current_topic = get_line_in_db($mysqli, "forum_topics", "topic_id", $idtopic);
$sujet = "";
$sous_sujet = "";




if (isset($variable_get['sousmod'])) {
    $sous_mood = get_alphanum($variable_get['sousmod']); //Citation, ou plus tard edit_topic
} else {
    $sous_mood = "";
}
if (isset($variable_post['mod'])){
    $mood = get_alphanum($variable_post['mod']); //Il existe trois modes.
}else{
    $mood="";
}
if ($mood == "" && $post_edit != 0 && $sous_mood != "cit") {
    $mood = "edit";
}
if ($mood == "" && $idtopic == 0 && $sous_mood != "cit") {
    $mood = "new_topic";
} else if ($mood == "") {
    $mood = "reponse";
}

if ($idforum == 0 && $idtopic != "" && $idtopic != 0) {
    $idforum = $current_topic['forum_id'];
}
$current_forum = get_line_in_db($mysqli, "forums", "forum_id", $idforum);

//Droits d'accès	
if ($current_forum['auth_view'] == '2' && $_SESSION['grad'] != "admin") {
    $result = mysqli_query_with_error($mysqli, "SELECT forum_id FROM forum_private WHERE forum_id ='{$current_forum['forum_id']}' AND user_id='{$_SESSION['id']}' LIMIT 1");
    if ($result->num_rows == 0) {
        header("Location: /");
        exit();
    }
}

//---------------------- Déf des fonctions.


function add_sondage_options($mysqli, $id_topi) {
    if (isset($_POST['new_opt'])) {
        $id_topi = get_num($id_topi);

        for ($i = 0; $i < count($_POST['new_opt']); $i++) {
            if ($_POST['new_opt'][$i] != "") {
                $reponse = $mysqli->real_escape_string(get_data_ss_tag($_POST['new_opt'][$i]));
                mysqli_query_with_error($mysqli, "INSERT INTO forum_sondage_result(topic_id, vote_option_text) VALUES('$id_topi', '$reponse')");
            }
        }
    }
}

function suivre_topic($mysqli, $id_topic){
    $suivi = mysqli_query($mysqli,"SELECT * FROM forum_topics_suivis WHERE topic_id=".$id_topic." AND user_id=".$_SESSION['id']);
    if ($suivi->num_rows==0){
        mysqli_query_with_error($mysqli, "INSERT INTO forum_topics_suivis (user_id,topic_id) values (".$_SESSION['id'].",".$id_topic.")");
        
    }
    
    //echo 'je suis';
}


function add_sondage($mysqli, $id_topi, $quest_sond) {
    $id_topi = get_num($id_topi);
    $quest_sond = $mysqli->real_escape_string(get_data_ss_tag($quest_sond));
    mysqli_query_with_error($mysqli, "UPDATE forum_topics SET topic_sondage='$quest_sond' WHERE topic_id='$id_topi';");
    add_sondage_options($mysqli, $id_topi);
}

function add_post($mysqli, $idtopic, $idforum) {
    $dat = strtotime("now");
    $idtopic = get_num($idtopic);
    $idforum = get_num($idforum);
    $messa = $mysqli->real_escape_string(get_data_ss_tag($_POST['message']));
    $autor = $mysqli->real_escape_string(get_data_ss_tag($_POST['login']));
    $ipp = $_SERVER['REMOTE_ADDR'];
    $dbbc = 1;
    if (isset($_POST['ncod'][0]) && $_POST['ncod'][0] == '1') {
        $dbbc = 0;
    }
    $dsmil = 1;
    if (isset($_POST['nsmil']) && $_POST['nsmil'] == '1') {
        $dsmil = 0;
    }

    if (empty($_SESSION['login'])) { //entrée du post
        mysqli_query_with_error($mysqli, "INSERT INTO forum_posts(topic_id, forum_id, post_time, poster_ip, post_username, post_text, enable_bbcode, enable_smilies)
		VALUES('$idtopic', '$idforum', '$dat', '$ipp', '$autor', '$messa', '$dbbc', '$dsmil')");
        $idPost=  mysqli_insert_id($mysqli);
    } else {
        mysqli_query_with_error($mysqli, "INSERT INTO forum_posts(topic_id, forum_id, poster_id, post_time, poster_ip, post_text, enable_bbcode, enable_smilies) 
		VALUES('$idtopic', '$idforum', '{$_SESSION['id']}', '$dat', '$ipp', '$messa', '$dbbc', '$dsmil')");
                $idPost=  mysqli_insert_id($mysqli);
        mysqli_query_with_error($mysqli, "UPDATE gens SET user_posts=(user_posts + 1) WHERE user_id='{$_SESSION['id']}'");
    }
    mysqli_query_with_error($mysqli, "UPDATE forum_topics SET topic_time='$dat' WHERE topic_id='$idtopic'"); //mise à jour du topic concernés
    suivre_topic($mysqli, $idtopic);
    return $idPost;
}



$messa = get_data_ss_tag($variable_post['message']);
//Droits d'accès
$erreur="";
if ($current_topic['topic_status'] == '1') {
    $erreur= "Ce topic est (ver)rouillé. Vous ne pouvez pas poster dedans.";
    
}elseif ($current_forum['forum_status'] == '1') {
    $erreur= "Ce forum est (ver)rouillé. Vous ne pouvez pas poster dedans.";
    
}elseif (get_line_numbers($mysqli, "forums", "forum_id", $idforum) == 0 || ($mood != "new_topic" && get_line_numbers($mysqli, "forum_topics", "topic_id", $idtopic) == 0) || ($mood == "edit" && get_data_in_db($mysqli, "forum_posts", "post_id", $post_edit, "topic_id") != $idtopic)) {
    $erreur= "Il semble y avoir eu une erreur de redirection, veuillez ré-essayer.";
    
}elseif ($mood == "edit" && (empty($_SESSION['login']) || ($_SESSION['grad'] != "admin" && !is_moderateur($mysqli, $_SESSION['id'], $idforum) && $_SESSION['id'] != get_data_in_db($mysqli, "forum_posts", "post_id", $post_edit, "poster_id")))) {
    $erreur=  "Vous n'avez rien à faire ici !";    
}elseif (trim($messa) != "" && $variable_post['idefix'] != md5(session_id() . $_SESSION['id'])) {
    $erreur= "Il semblerai que vous ayez été victime d'une tentative de piratage. 
La page où vous étiez précédemment a été créée pour détourner votre session.";
    
}elseif (empty($_SESSION['login']) && $mood == "new_topic") {
    $erreur= "Veuillez vous inscrire et vous connecter pour écrire 
un nouveau sujet";    
}elseif ($current_forum['auth_post'] != '0' && empty($_SESSION['login'])) {
    $erreur = "Veuillez vous inscrire et vous connecter pour écrire 
un nouveau sujet";    
}else{
//echo 'salut';

$dat = strtotime("now");
$autor = get_data_ss_tag($variable_post['login']);
if (isset($variable_post['qsond'])) {
    $quest_sond = get_data_ss_tag($variable_post['qsond']);
} else {
    $quest_sond = "";
}

$dbbc = 1;
if (isset($_POST['ncod'][0]) && $_POST['ncod'][0] == '1') {
    $dbbc = 0;
}
$dsmil = 1;
if (isset($_POST['nsmil']) && $_POST['nsmil'] == '1') {
    $dsmil = 0;
}
$ipp = $_SERVER['REMOTE_ADDR'];
$posty = "";
$iddpost = "";
$spam = false;


if ($mood == "edit") {
    $result = mysqli_query_with_error($mysqli, "SELECT post_id FROM forum_posts WHERE topic_id='" . $idtopic . "' ORDER BY post_id LIMIT 1");
    $first_post = $result->fetch_assoc();
    if ($first_post['post_id'] == $post_edit) {
        $sous_mood = "edit_topic";
    }
}

if (trim($messa) != "" && $mood != "edit") {
    //Anti-spam
    $date_limite = $dat - 20;
	//$result = mysqli_query_with_error($mysqli, "SELECT post_id FROM forum_posts WHERE (poster_id = '{$_SESSION['id']}' OR poster_ip = '$ipp') AND post_time > $date_limite LIMIT 1"); TODO remettre l'IP, comme là.
    $result = mysqli_query_with_error($mysqli, "SELECT post_id FROM forum_posts WHERE (poster_id = '{$_SESSION['id']}') AND post_time > $date_limite LIMIT 1");
    if ($result->num_rows != 0) {
        $erreur= "Veuillez attendre au moins une trente secondes entre deux posts, merci";
        $spam = true;
    }
}

if (isset($variable_post['sujett'])) {
    $sujet = $mysqli->real_escape_string(get_data_ss_tag($variable_post['sujett']));
    $sous_sujet = $mysqli->real_escape_string(get_data_ss_tag($variable_post['sousujett']));
}
//cas dun edit
if (trim($messa) != "" && ($mood == "edit") && !$spam) {
    //echo " salut2 ";
    $messa = $mysqli->real_escape_string($messa);
    //entrée du post
    mysqli_query_with_error($mysqli, "UPDATE forum_posts SET post_edit_count=(post_edit_count + 1), enable_bbcode='$dbbc', enable_smilies='$dsmil', post_text='$messa', post_edit_time='$dat' WHERE post_id='$post_edit'");

    if ($sous_mood == "edit_topic") {
        //entrée éventuelle du titre et sous-titre
        mysqli_query_with_error($mysqli, "UPDATE forum_topics SET topic_title='$sujet', topic_sub_title='$sous_sujet' WHERE topic_id='$idtopic'");

        //si sondage?
        $sondu = 0;
        if ($quest_sond != "") {
            $sondu = 1;
        }
        if ($current_topic['topic_sondage'] != "" && $sondu == '0') { //cas de la suppression du sondage
            delete_sondage($mysqli, $idtopic);
        } else if ($current_topic['topic_sondage'] == "" && $sondu == '1') { //Cas d'un nouveau sondage.
            add_sondage($mysqli, $idtopic, $quest_sond);
        } else if ($current_topic['topic_sondage'] != "" && $sondu == '1') { //Cas d'une modif d'un sondage existant'
            $quest_sond = $mysqli->real_escape_string($quest_sond);
            mysqli_query_with_error($mysqli, "UPDATE forum_topics SET topic_sondage='$quest_sond' WHERE topic_id='$idtopic'");
            $old_option = mysqli_query_with_error($mysqli, "SELECT * FROM forum_sondage_result WHERE topic_id=" . $idtopic);
            while ($ligne = $old_option->fetch_assoc()) {
                if (isset($_POST['sup_opt'][$ligne['vote_option_id']])) {
                    mysqli_query_with_error($mysqli, "UPDATE forum_sondage_result SET vote_option_text='" . $mysqli->real_escape_string($_POST['sup_opt'][$ligne['vote_option_id']]) . "' WHERE vote_option_id=" . $ligne['vote_option_id']);
                } else {
                    mysqli_query_with_error($mysqli, "DELETE FROM forum_sondage_result WHERE vote_option_id=" . $ligne['vote_option_id']);
                }
            }
            add_sondage_options($mysqli, $idtopic); //TODO Pas sur que ça fonctionne ça, pour l'édition des réponses. On dirai juste qu'on rajoute des options en double.

            for ($i = 0; $i < count($variable_post['sup_opt']); $i++) {
                if (isset($variable_post['sup_opt'])) {
                    continue;
                }
                $num_opt = get_num($variable_post['sup_opt'][$i]);
                mysqli_multi_query_with_error($mysqli, "DELETE FROM  forum_sondage_result WHERE topic_id='$idtopic' AND vote_option_id='$num_opt'; 
				DELETE FROM  forum_sondage_voters WHERE topic_id='$idtopic' AND vote_option_id='$num_opt'");
            }
        }
    }
    $posty = $idtopic;
}

//cas dune réponse
if (trim($messa) != "" && $mood == "reponse" && !$spam) {
    $new_post=add_post($mysqli, $idtopic, $idforum);
    $posty = $idtopic;
}

//cas dun new topic
if (trim($messa) != "" && $mood == "new_topic" && $variable_post['sujett'] != "" && !$spam) {
    //entrée du topic
    mysqli_query_with_error($mysqli, "INSERT INTO forum_topics(forum_id, topic_title, topic_sub_title, topic_poster) VALUES('$idforum', '$sujet', '$sous_sujet', '{$_SESSION['id']}')");
    $result = mysqli_query_with_error($mysqli, "SELECT topic_id FROM forum_topics WHERE topic_poster='{$_SESSION['id']}' ORDER BY topic_id DESC LIMIT 1");
    $topi = $result->fetch_assoc(); //Puis on récupère l'id du topic ainsi créé afin de l'attribuer au premier post.
    add_post($mysqli, $topi['topic_id'], $idforum);

    if ($quest_sond != "") {
        add_sondage($mysqli, $topi['topic_id'], $quest_sond);
    }

    $posty = $topi['topic_id'];
}

if ($posty != "") { //TODO rediriger direct vers la fin du topic sans afficher ça (de toute façon, $iddpost n'est plus valide, à virer)
    //echo " salut3 ";
    if ($sous_mood == "edit_topic") {
        //echo " salut4 ";
       header('Location: topic.php?id='.$posty);
    } else if ($mood == "edit") {
        //echo " salut5 ";
        header('Location: topic.php?id='.$posty.'&m='.$post_edit.'#'.$post_edit);
    } else if ($mood == "new_topic") {
        //echo " salut6 ";
        header('Location: topic.php?id='.$posty);
    } else if ($idtopic != "") {
        //echo " salut7 ";
        //echo 'Location: topic.php?id='.$posty.'&m='.$new_post.'#'.$new_post;
        header('Location: topic.php?id='.$posty.'&m='.$new_post.'#'.$new_post);
    }           
        
    exit;
}
}
//----------------------------------------------------------------------------------
entete($mysqli, "Nouveau sujet");
javascript_BBcode();
if ($erreur!=""){
    echo '<center><div id="boite_feedback">'.$erreur."</div></center>";
    if ($spam!=true){
        echo "</div></div>";
    show_footer();
    exit;
    }
}
?>
<form id="message" name="formul" class="post ombre" action="post.php" method="POST">
<?php
$nom_forum = get_data_in_db($mysqli, "forums", "forum_id", $idforum, "forum_name");
echo '<h4 class="ombre"><a href="forum.php?id=' . $idforum . '">' . $nom_forum . '</a><span class="bleuf"> ::: </span>';
if ($mood == "new_topic") {
    echo 'Nouveau sujet</h4>';
} else {
    $nom_topic = get_data_in_db($mysqli, "forum_topics", "topic_id", $idtopic, "topic_title");
    echo '<a href="topic.php?id=' . $idtopic . '">'.$nom_topic . '</a><span class="bleuf"> ::: </span>';
    if ($sous_mood == "edit_topic") {
         echo 'Editer un sujet</h4>';
    } else if ($mood == "edit") {
        echo 'Editer un message</h4>';
    } else {
        echo 'Nouveau message</h4>';
    }
}

if ($messa == "") { //Sinon c'est que l'utilisateur a déjà envoyé le formulaire une fois. Cas inexistant si pas de bug, mais on sait jamais.
    if ($sous_mood == "cit") {
        $post_cite = get_line_in_db($mysqli, "forum_posts", "post_id", $post_edit);
        $auteur_name = get_data_in_db($mysqli, "gens", "user_id", $post_cite['poster_id'], "username");
        $teuxt = get_data_propre_sortie_db($post_cite['post_text']);
        $messa = "[quote=\"$auteur_name\"]" . $teuxt . "[/quote]";
    } else if ($mood == "edit") {
        $pos = get_line_in_db($mysqli, "forum_posts", "post_id", $post_edit);
        $messa = get_data_propre_sortie_db($pos['post_text']);
        $dbbc = $pos['enable_bbcode'];
        $dsmil = $pos['enable_smilies'];
        $sujet = get_data_propre_sortie_db($current_topic['topic_title']);
        $sous_sujet = get_data_propre_sortie_db($current_topic['topic_sub_title']);
    }
}
?>
    
    <input type='hidden' name='topic' value='<?php echo $idtopic ?>'>
    <input type='hidden' name='frum' value='<?php echo $idforum ?>'>
    <input type='hidden' name='mod' value='<?php echo $mood ?>'>
    <input type='hidden' name='pos' value='<?php echo $post_edit ?>'>
    <input type='hidden' name='page' value='<?php echo $page ?>'>
    <input type='hidden' name='idefix' value='<?php echo md5(session_id() . $_SESSION['id']) ?>'>    

    <p class="informations">
        <!-- Information Utilisateur et Topic -->
<?php
if (empty($_SESSION['login'])) {
    ?>
            <label for="pseudo">Pseudo</label><input id="pseudo" type="text" name="pseudo" maxlength="50"><br/>';
            <?php
        } else {
            ?>
            <input type='hidden' name='login' value='<?php echo $_SESSION['login'] ?>'>
            <?php
        }
        if ($mood == "new_topic" || $sous_mood == "edit_topic") {
            ?>
            <label for="titre">Titre</label>
            <input id="titre" type="text" name="sujett" value="<?php echo $sujet ?>" maxlength="40"/><br/>
            <label for="sous-titre">Sous-titre</label>
            <input id="sous-titre" type="text" name="sousujett" value="<?php echo $sous_sujet ?>" maxlength="60"/>
    <?php
}
?>
    </p>
    <!-------------------------------------->
        <?php
        display_post_message($dbbc, $dsmil, $messa, $mysqli);

        if ($mood == "new_topic" || $sous_mood == "edit_topic") {

            $opt = array();
            $quest_sond = "";
            if ($current_topic['topic_sondage'] != "") {
                $quest_sond = get_data_propre_sortie_db($current_topic['topic_sondage']);
                $result = mysqli_query_with_error($mysqli, "SELECT * FROM forum_sondage_result WHERE topic_id='$idtopic'");
                while ($ligne = $result->fetch_assoc()) {
                    $opt[] = $ligne;
                }
            }
            ?>

        <div id="sondage" class="ombre">
        <?php
        if ($quest_sond != "") {
            $sondage_actif = "sondage_contenu_actif";
            echo '<h5 id="titre_sondage" class="ombre actif">Sondage</h5>';
        } else {
            $sondage_actif = "";
            echo '<h5 id="titre_sondage" class="ombre">Ajouter un sondage</h5>';
        }
        ?>
            <div id="contenu_sondage" class="sondage_contenu <?php echo $sondage_actif ?>">

                <label for="question">Question du sondage</label>
                <input id="question" type="text" name="qsond" maxlength="140" value="<?php echo $quest_sond ?>" class="texte"/>
                
                <div id="choix">
    <?php
    for ($i = 0; $i < count($opt); $i++) {

        echo '<label id="label_choix' . $i . '" for="choix' . $i . '">Choix n°' . ($i + 1) . '</label>';
        echo '<input id="choix' . $i . '" type="text" name="sup_opt[' . $opt[$i]['vote_option_id'] . ']" value="' . $opt[$i]['vote_option_text'] . '" class="texte rempli" /><button class="supprimer_choix" id="supprimer_choix' . $i . '" name="supprimer_choix" value="" ></button>';
        echo '<script>
                $(\'#supprimer_choix' . $i . '\').click(function(){
                   $(\'#label_choix' . $i . '\').remove();
                   $(\'#choix' . $i . '\').remove();
                   $(\'#supprimer_choix' . $i . '\').remove();
                });
                </script>';
    }

    for ($i = $i; $i < 3; $i++) {
        echo '<label for="choix' . $i . '">Choix n°' . ($i + 1) . '</label>';
        echo '<input id="choix' . $i . '" type="text" name="new_opt[]" value="" class="texte" />';
    }
    ?>
                </div>
                <input type="hidden" name="nbChoix" value="<?php echo $i ?>" id="nbChoix" />
                <ul class="actions">
                    <li class="btn ombre"><input id='add_choix' type="button" value="Ajouter un choix">
                        <script>
                            $('#add_choix').click(function() {
                                var nbChoix = eval($("#nbChoix").attr('value'));
                                $("#choix").append('<label for="choix' + (nbChoix + 1) + '">Choix n°' + (nbChoix + 1));
                                $("#choix").append('<input id="choix' + (nbChoix + 1) + '" type="text" name="sup_opt[]" value="" class="texte" />');
                                $("#nbChoix").attr('value', (nbChoix + 1));
                            });
                        </script>

                    </li>
                    <script>

                    </script>
                    <li class="btn ombre petit_bleu droit "><input type="submit" value="Supprimer le sondage"></li>
                </ul>
            </div>

        </div>
        <script>
            $('#titre_sondage').click(function() {
                $('#titre_sondage').toggleClass('actif');
                $('#contenu_sondage').toggleClass('sondage_contenu_actif');
            });
        </script>

    <?php
}
?>
                <ul class="actions">
                    <li><input type="checkbox" name="auto" value="auto" name="nsmil" id="smiley_off"><label for="smiley_off">Désactiver les smileys</label></li>
                    <li class="btn ombre droit"><input type="submit" value="Envoyer"></li>
                    <!--<li class="btn ombre droit"><input type="submit" value="Prévisualiser"></li>-->
                </ul>
            </form>
            </div> <!-- fin div contenu-->
        </div> <!-- fin div corps-->

<?php
show_footer();
?>